package com.fei.wechat.common.util;

import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 描述: 校验实体对象
 * 版权: Copyright (c) 2018 
 * 公司: 飞翔科技 
 * 作者: 张进飞 
 * 版本: 1.0 
 * 创建日期: 2018年4月22日 
 * 创建时间: 下午9:04:48
 */
public class BeanValidation<T>
{
    
    private ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    
    private Validator validator = factory.getValidator();
    
    private Set<ConstraintViolation<T>> errors;
    
    private T t;
    
    public boolean hasError()
    {
        this.errors = validator.validate(t);
        if (errors != null && errors.size() > 0)
        {
            return true;
        }
        return false;
    }
    
    public BeanValidation(T t)
    {
        this.t = t;
    }
    
    public String getError()
    {
        Iterator<ConstraintViolation<T>> it = errors.iterator();
        ConstraintViolation<T> oldObject = (ConstraintViolation<T>) it.next();
        return oldObject.getMessage();
    }
    
    public static String getError(BindingResult result)
    {
        List<ObjectError> list = result.getAllErrors();
        return list.get(0).getDefaultMessage();
    }
    
    public List<ObjectError> getAllErrors()
    {
        List<ObjectError> list = new ArrayList<ObjectError>();
        Iterator<ConstraintViolation<T>> it = errors.iterator();
        while (it.hasNext())
        {
            ConstraintViolation<T> oldObject = (ConstraintViolation<T>) it.next();
            ObjectError objectError = new ObjectError(oldObject.getPropertyPath().toString(), oldObject.getMessage());
            list.add(objectError);
        }
        return list;
    }
    
}
